using EnterpriseWebsiteUtil.Helper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Converters;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using EnterpriseWebsiteApi.ActionFilters;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace EnterpriseWebsiteApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddRazorPages()
                .AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    options.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm" });
                });
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins", builder =>
                {
                    builder.AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                });
            });
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "Francis Enterprises API",
                    Version = "v1",
                    Description = "华麟API",
                    Contact = new OpenApiContact
                    {
                        Email = "1839768883@qq.com",
                        Name = "BenLi",
                    },
                    License = new OpenApiLicense
                    {
                        Name = "BROOKE֤",
                    }
                });
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            //过滤器注入
            services.AddScoped<LanguageHeaderFilter>();
            services.AddScoped<JwtAuthorizeFilter>();
            //依赖注入
            var assemblyNames = new string[] { "EnterpriseWebsiteBLL", "EnterpriseWebsiteUtil" };
            foreach (var name in assemblyNames)
            {
                var types = Assembly.Load(name).GetTypes();
                foreach (var t in types)
                {
                    if (t.IsEnum || t.IsAbstract && t.IsSealed) // 如果是枚举类型或静态类
                    {
                        continue;
                    }
                    else if (!t.IsDefined(typeof(AttributeUsageAttribute), false))
                    {
                        services.AddTransient(t);
                    }
                }
            }
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //// 启用身份验证中间件
            //app.UseAuthentication();

            //// 启用授权中间件
            //app.UseAuthorization();

            app.UseRouting();

            app.UseAuthorization();

            app.UseDefaultFiles();

            app.UseSwagger();

            app.UseStaticFiles();

            //app.UseCors("CorsPolicy");

            app.UseCors("AllowAllOrigins");

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Francis Enterprises API V1");
                c.RoutePrefix = "api";
            });
        }
    }
}
